﻿import QtQuick 2.7
import QtQuick.Window 2.0
import QtQuick.VirtualKeyboard 2.3
import QtQuick.VirtualKeyboard.Settings 2.2
import Qt5.VirtualKeyboald 1.0

Rectangle {
    id:root
    color: "#3c3c3c"
    
    TextInput{
        id: textInput
        anchors.fill: parent
        horizontalAlignment: TextInput.AlignLeft
        verticalAlignment: TextInput.AlignTop
        visible: ((InputContext.inputMethodHints & Qt.ImhDigitsOnly) ||
                  (InputContext.inputMethodHints & Qt.ImhFormattedNumbersOnly)) ? false : true
        readOnly: true
        cursorVisible: false
    }

    InputPanel {
        signal closeKeyBoard();
        property int pressKey: -1
        //不直接和InputPanel的visible绑定，避免出现输入面板和控件本身显隐不一致的问题
        property bool inputpanelVisible: Qt.inputMethod.visible
        width: 1024
        
        id: inputPanel
        y:root.height-height        //当切换控件时，会重新依据x，y来渲染
//        width: ((InputContext.inputMethodHints & Qt.ImhDigitsOnly) ||
//                (InputContext.inputMethodHints & Qt.ImhFormattedNumbersOnly)) ? 370 : root.width
        
        states: State {
            name: "visible"
            when: inputPanel.active
            PropertyChanges {
                target: inputPanel
                y: root.height - inputPanel.height
            }
        }
         
        transitions: Transition {
            from: ""
            to: "visible"
            reversible: true
            ParallelAnimation {
                NumberAnimation {
                    properties: "y"
                    duration: 250
                    easing.type: Easing.InOutQuad
                }
            }
        }
        
        onInputpanelVisibleChanged: {
            //现在在状态发生改变时，只有点击I了隐藏或回车才会关闭软键盘
            if (Qt.Key_Escape == pressKey
                    || Qt.Key_Return == pressKey)
            {
                if (!inputpanelVisible)
                {
                    closeKeyBoard()
                }
            }
        }

        Component.onCompleted: {
            InputContext.animating = false

            // en_GB:英语    zh_CN:中文   es_ES:西班牙
            VirtualKeyboardSettings.activeLocales = ["en_GB", "zh_CN"];
            VirtualKeyboardSettings.locale = "en_GB"
        }
    }
    
    Connections{
        target: inputPanel
        onCloseKeyBoard:{
            /*此处直接调用输入面板进行隐藏
            */
            VirtualKeyboald.close();
            inputPanel.pressKey = -1
        }
    }
    
    Connections{
        target: InputContext.inputEngine
        onActiveKeyChanged: {
            if (Qt.Key_Escape == key)               //隐藏按钮稍特殊，需要直接关闭输入框
            {
                inputPanel.pressKey = key
                InputContext.commit()               //必须添加此方法，否则特定情况下，弹出软键盘后处于鼠标按下的状态
            }
            if (Qt.Key_Return == key)
            {
                inputPanel.pressKey = key
                InputContext.commit()
            }
        }
    }
}
